package com.ttg.utils.connection.handler;


import com.ttg.utils.Bytes;
import com.ttg.utils.ZipUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class ParamsAndZipFileResponseHandler implements ResponseHandler<ParamsAndFileHttpResponse> {
    private final File downloadFile;

    public ParamsAndZipFileResponseHandler(File downloadFile) {
        if(downloadFile != null && (!downloadFile.exists() || !downloadFile.isDirectory())) {
            this.downloadFile = downloadFile;
        } else {
            throw new IllegalArgumentException("The downloadFile is required; it must not be null or directory.");
        }
    }

    public ParamsAndFileHttpResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        HttpEntity entity = null;
        ParamsAndFileHttpResponse result = null;

        ParamsAndFileHttpResponse var10;
        try {
            entity = ResponseHandlerHelper.handleNon2xxStatus(response);
            Charset responseCharset = ResponseHandlerHelper.getResponseCharset(entity);
            result = new ParamsAndFileHttpResponse(responseCharset);
            byte[] exceptionInfo = ResponseHandlerHelper.handleCustomExceptionStatus(response);
            if(exceptionInfo != null) {
                result.setByteResult(exceptionInfo);
                ParamsAndFileHttpResponse in1 = result;
                return in1;
            }

            InputStream in = entity.getContent();
            byte[] buffer = new byte[4];
            int actualReadLength = Bytes.readInputStreamToArray(in, buffer, 4);
            if(actualReadLength != 4) {
                throw new HttpResponseException(500, "响应数据的格式不符合接口规范,byte[]前4位应该是表示参数内容的长度,但实际上没有读取到4位.");
            }

            int parametersBytesLength = Bytes.bytes2int(buffer);
            buffer = new byte[parametersBytesLength];
            actualReadLength = Bytes.readInputStreamToArray(in, buffer, parametersBytesLength);
            if(actualReadLength != parametersBytesLength) {
                throw new HttpResponseException(500, "响应数据的格式不符合接口规范,byte[]前4位显示参数内容长度为[" + parametersBytesLength + "],但实际上没有读到这么长的内容.");
            }

            result.setByteResult(buffer);
            ZipUtils.doDecompressToFile(in, this.downloadFile);
            result.setDownlaodFile(this.downloadFile);
            var10 = result;
        } finally {
            EntityUtils.consume(entity);
        }

        return var10;
    }
}
